package com.sunriz.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunriz.domain.MCinfo;
import com.sunriz.service.CtrlService;
import com.sunriz.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: weizs
 * @Create: 2023/11/13
 * @Description:
 */
@RestController
@RequestMapping("/report")
public class ReportController {


    @Autowired
    private ReportService reportService;

    @PostMapping("/send/datareport")
    public List<MCinfo> report() throws JsonProcessingException {
        List<MCinfo> list = reportService.select();

        ObjectMapper mapper = new ObjectMapper();
        List<Object> objects = new ArrayList<>();
        objects.add(list);
        StringBuilder jsonString = new StringBuilder();
        for (Object obj : objects) {
            jsonString.append(mapper.writeValueAsString(obj)).append(",");
        }
        // 构建POST请求的参数
        String finalJsonString = jsonString.toString().replaceAll(",$", "");
        String json = finalJsonString.substring(1, finalJsonString.length() - 1);
        System.out.println(json);
        // 定义接口地址
        String apiUrl = "http://192.168.10.59:48800/iot/api/wot/{tdCode}/{deviceCode}/propertyStatus/";
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes());
            os.flush();

            int responseCode = conn.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 读取响应内容
            StringBuilder response = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            }
            System.out.println("Response Content: " + response.toString());
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
